package blockchain.dao.rocksDB;

import blockchain.dao.DAOService;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.testng.util.Strings;

import java.io.UnsupportedEncodingException;

/**
 * @Author: 李浩然
 * @Date: 2021/3/9 8:05 下午
 */
@Component
public class RocksdbDAO implements DAOService {
    private Logger logger = LoggerFactory.getLogger(RocksdbDAO.class);

    private RocksDB rocksDB;

    private static final String CHARSET = "utf-8";

    public RocksdbDAO() {
        try {
            RocksDB.loadLibrary();
            rocksDB = RocksDB.open("./rocksDB");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void put(String key, String value) {
        if (Strings.isNullOrEmpty(key) || Strings.isNullOrEmpty(value)) return;
        try {
            rocksDB.put(key.getBytes(CHARSET), value.getBytes(CHARSET));
        } catch (RocksDBException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public String get(String key) {
        if (Strings.isNullOrEmpty(key)) return null;
        try {
            byte[] bytes = rocksDB.get(key.getBytes(CHARSET));
            if (bytes != null) {
                return new String(bytes);
            }
        } catch (RocksDBException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void delete(String key) {
        if (Strings.isNullOrEmpty(key)) return;
        try {
            rocksDB.delete(rocksDB.get(key.getBytes(CHARSET)));
        } catch (RocksDBException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws RocksDBException {
        RocksdbDAO dao = new RocksdbDAO();
        String val = dao.get("05093fc3907aab88fbd535d057b543d6a063e01dbb13e0add1aac686b7517265");
        System.out.println(val);
    }
}
